<?php
/**
 * @Author: gan
 * @Description: 腾讯云cos
 * @File:  CosAdapter
 * @Version: 1.0.0
 * @Date: 2021/12/27 9:15 上午
 */
declare(strict_types=1);

namespace RX\Component\Upload\Impl;

use Qcloud\Cos\Client;
use QCloud\COSSTS\Sts;
use RX\Enums\UploadEnum;
use RX\Exception\BizException;
use RX\Helpers\StringHelper;

class CosImpl implements UploadInterface
{
    private string  $secretId;
    private string  $secretKey;
    private string  $bucket;
    private string  $region;
    private string  $domain;
    private int     $durationSeconds = 1800;
    protected array $allowActions    = [
        // 简单上传
        'name/cos:PutObject',
        'name/cos:PostObject',
        // 分片上传
        'name/cos:InitiateMultipartUpload',
        'name/cos:ListMultipartUploads',
        'name/cos:ListParts',
        'name/cos:UploadPart',
        'name/cos:CompleteMultipartUpload'
    ];

    public function __construct(array $config = [])
    {
        if (empty($config)) {
            $config = StringHelper::config('upload.cos');
        }
        $this->secretId  = $config["secretId"];
        $this->secretKey = $config["secretKey"];
        $this->bucket    = $config["bucket"];
        $this->domain    = $config["domain"];
        $this->region    = $config["region"];
    }

    public function stsData()
    {
        $sts    = new Sts();
        $config = array(
            'url'             => 'https://sts.tencentcloudapi.com/',
            'proxy'           => '',
            'secretId'        => $this->secretId,
            'secretKey'       => $this->secretKey,
            'bucket'          => $this->bucket,
            'region'          => $this->region,
            'allowPrefix'     => "",
            'durationSeconds' => $this->durationSeconds,
            'allowActions'    => $this->allowActions
        );
        return $sts->getTempKeys($config);
    }


    public function uploadFile(array $params)
    {
        $object   = $params["object"] ?? null;
        $filePath = $params["filePath"] ?? null;
        if (empty($object) || empty($filePath)) {
            throw new BizException(UploadEnum::class, UploadEnum::PUT_OBJECT_PARAMS_ERROR);
        }

        $cosClient = new Client(['region'      => $this->region,
                                 'schema'      => 'https',
                                 'credentials' => [
                                     'secretId'  => $this->secretId,
                                     'secretKey' => $this->secretKey
                                 ]]);
        return $cosClient->upload($this->bucket, $object, fopen($filePath, 'rb'));
    }

    public function domain()
    {
        return $this->domain;
    }
}
